package cn.mgm.senior.dao;

import cn.mgm.senior.util.JDBCUtilV2;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BaseDAO {

    public int updateExecute(String  string,Object... params) throws SQLException {
        Connection connection = JDBCUtilV2.getConnection();

        PreparedStatement preparedStatement = connection.prepareStatement(string);

        if (params!=null && params.length>0){
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i+1,params[i]);
            }
        }


        int i = preparedStatement.executeUpdate();

        preparedStatement.close();
        JDBCUtilV2.release();

        return i;
    }


    public <T> List<T> executeQuery(Class<T> clazz,String sql,Object ... params) throws Exception {
        Connection connection = JDBCUtilV2.getConnection();

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        if (params!=null && params.length>0){
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i+1,params[i]);
            }
        }


        ResultSet resultSet = preparedStatement.executeQuery();
        // 获取结果集中元数据对象
        ResultSetMetaData metaData = resultSet.getMetaData();
        // 包含了列的名称 列的数量
        int columnCount = metaData.getColumnCount();
        List<T> list = new ArrayList<>();
        while (resultSet.next()){
            // 处理结果
            T t= clazz.getDeclaredConstructor().newInstance();

            for (int i = 1; i <= columnCount; i++) {
                // 通过下标获取列的值
                Object value = resultSet.getObject(i);
                //获取到列的 value 值,这个值就是 t 这个对象中的某一个属性
                // 获取当前拿到的名字 = 对象的属性名
                String fieldName = metaData.getColumnLabel(i);
                //通过类对象和 fieldName 获取要封装的对象的属性
                Field field = clazz.getDeclaredField(fieldName);
                // 突破封装的 private
                field.setAccessible(true);
                field.set(t,value);
            }
            list.add(t);
        }
        resultSet.close();
        preparedStatement.close();
        JDBCUtilV2.release();
        return  list;
        
    }



    public <T> T executeQueryBean(Class<T> clazz,String sql,Object...params) throws Exception{
        List<T> list= this.executeQuery(clazz,sql,params);
        if (list ==null || list.isEmpty()){
            return  null;
        }
        return list.getFirst();
    }

}
